import type { App, Directive, DirectiveBinding } from 'vue'
import { intersection } from 'lodash-es'
import { userStore } from '@/store/modules/user'
import { isArray } from '@/utils/is'

function hasPermission(value?: string | string[], def = true): boolean {
  if (!value) {
    return def
  }
  const userModule = userStore()
  const allCodeList = userModule.permissionActionList
  if (!isArray(value)) {
    return allCodeList.includes(value)
  }
  return (intersection(value, allCodeList) as string[]).length > 0
}

const authDirective: Directive = {
  mounted: (el: Element, binding: DirectiveBinding<any>) => {
    const value = binding.value
    if (!value) return
    if (!hasPermission(value)) {
      el.parentNode?.removeChild(el)
    }
  }
}

export function setupPermissionDirective(app: App) {
  app.directive('auth', authDirective)
}
